package com.matrix.draft.sockettest.day9;

import com.matrix.draft.sockettest.day9.pojo.GlobalProto;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;

/**
 * 多类型的protobuf序列化传输
 */
public class MultiProtoServer {
    private String HOST = "127.0.0.1";
    private Integer PORT = 8080;

    public void run() {
        EventLoopGroup masterGroup = null;
        EventLoopGroup slaverGroup = null;
        ServerBootstrap serverBootstrap = null;
        ChannelFuture cf = null;
        try {
            masterGroup = new NioEventLoopGroup(1);
            slaverGroup = new NioEventLoopGroup();
            serverBootstrap = new ServerBootstrap()
                    .group(masterGroup, slaverGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) {
                            // In Bound Handlers
                            ch.pipeline().addLast("protoDecoder", new ProtobufDecoder(GlobalProto.Global.getDefaultInstance()));
                            ch.pipeline().addLast("protoServerHandler", new MultiProtoServerHandler());
                            // Out Bound Handlers
                        }
                    });
            cf = serverBootstrap.bind(HOST, PORT).sync();
            System.err.println("Protobuf Server is running...");
            cf.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            masterGroup.shutdownGracefully();
            slaverGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new MultiProtoServer().run();
    }
}
